Skip to content

fix: workshop 05 invoke agent script#697

Open
2dukes wants to merge 1 commit intoaws-samples:mainfrom
2dukes:fix/05-invoke-agent-script
Open

fix: workshop 05 invoke agent script#697
2dukes wants to merge 1 commit intoaws-samples:mainfrom
2dukes:fix/05-invoke-agent-script

Conversation

@2dukes
Copy link
Copy Markdown

@2dukes 2dukes commented Mar 21, 2026

Issue #, if available: N/A

Description of changes:

Fixed the invoke_agent function in the Jupiter Notebook to properly handle event streamed response chunks from the Bedrock Agent Runtime API by accumulating all response chunks into a single agent_answer string variable instead of returning on the first chunk, which could result in truncated responses.

The final function code is as follows:

def invokeAgent(query, session_id, enable_trace=False, session_state=dict()):
    end_session:bool = False
    
    # invoke the agent API
    agentResponse = bedrock_agent_runtime_client.invoke_agent(
        inputText=query,
        agentId=agent_id,
        agentAliasId=alias_id, 
        sessionId=session_id,
        enableTrace=enable_trace, 
        endSession= end_session,
        sessionState=session_state
    )
    
    if enable_trace:
        logger.info(pprint.pprint(agentResponse))
    
    event_stream = agentResponse['completion']
    try:
        agent_answer = ""
        for event in event_stream:        
            if 'chunk' in event:
                data = event['chunk']['bytes']
                chunk_text = data.decode('utf8')
                agent_answer += chunk_text

                if enable_trace:
                    logger.info(f"Chunk received ->\n{chunk_text}")
            elif 'trace' in event:
                if enable_trace:
                    logger.info(json.dumps(event['trace'], indent=2, cls=DateTimeEncoder))
            else:
                raise Exception("unexpected event.", event)

            if enable_trace:
                logger.info(f"Final answer ->\n{agent_answer}")
            
            return agent_answer
    except Exception as e:
        raise Exception("unexpected event.", e)

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

@review-notebook-app
Copy link
Copy Markdown

Check out this pull request on  ReviewNB

See visual diffs & provide feedback on Jupyter Notebooks.


Powered by ReviewNB

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant